<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>

<body>
	<template id="custom-title-template">
		<style>
			h1 {
				font-size: 40px;
				color: #000;
			}
		</style>
		<h1>Hello WC!</h1>
	</template>
	<template id="my-paragraph">
		<style>
			p {
				color: white;
				background-color: #666;
				padding: 5px;
			}
		</style>
		<p>
			<slot name="my-text">My default text</slot>
		</p>
	</template>
	<custom-title></custom-title>
	<my-paragraph>
		<p slot="my-text">Let's have some different text!1</p>
		<p slot="my-text">Let's have some different text!2</p>
		<p slot="my-text">Let's have some different text!3</p>
	</my-paragraph>
	<script>
		/**
		 * template：模板，通过id获取插入到自定义的组件中
		 * slot：插槽，用作灵活的插入外部传入的dom元素
		 * attachShadow：定义影子dom的类型，mode为open，外部可操作，mode为close外部不可操作
		 * 生命周期函数：
		 * 1.connectedCallback
		 * 2.disconnectedCallback
		 * 3.attributeChangedCallback
		 * 4.
		 */
		class CustomTitle extends HTMLElement {
			constructor() {
				super()
				this.attachShadow({
					mode: 'open'
				})
				const tmpl = document.querySelector('#custom-title-template')
				this.shadowRoot.appendChild(tmpl.content.cloneNode(true))
				this.addEventListener('click', e => {
					this.disabled = !this.disabled
					this.nbattribute = 'test'
					console.log('clicked', this.disabled)
				})
			}
			connectedCallback() {
				console.log('start');
				//...
			}

			disconnectedCallback() {
				console.log('end');
				//...
			}
			get nbattribute() {
				console.log('?')
				return this.getAttribute('nbattribute')
			}

			set nbattribute(value) {
				console.log('?!')
				this.setAttribute('nbattribute', value)
			}

			get disabled() {
				console.log('?')
				return this.getAttribute('disabled')
			}

			set disabled(value) {
				console.log('?!')
				this.setAttribute('disabled', value)
			}
			static get observedAttributes() {
				return ['disabled', 'nbattribute']
			}
			attributeChangedCallback(attrName, oldVal, newVal) {
				console.log(attrName, oldVal, newVal);
				//...
			}
		}
		customElements.define('my-paragraph',
			class extends HTMLElement {
				constructor() {
					super();

					const template = document.getElementById('my-paragraph');
					const templateContent = template.content;

					this.attachShadow({
						mode: 'open'
					}).appendChild(
						templateContent.cloneNode(true)
					);
				}
			}
		);
		customElements.define('custom-title', CustomTitle);
	</script>
</body>

</html>